import "module-alias/register";
import "express-async-errors";
const argv = require("minimist")(process.argv.slice(2));
import { state } from "./state";
state.ENV = argv?.ENV || "";
import { getApp, MasReq, MasRes, getApiRouter } from "mas-server";
import path from "path";
import { openCors } from "./middleware/openCors";
import serverConfig, { configPath } from "@@/config/serverConfig/config";
import { initDirty } from "./utils/dirty";
import { initMemoryCache } from "./utils/memoryCache";
import express from "express";
import { createApiDoc } from "mas-api-web";
import { pathCN } from "@@/config/apiDocConfig/config";
import { init_masSql } from "./utils/mas-sql";

console.log("当前环境：", state.ENV);
// 初始化数据库
init_masSql();
// 使用脏数据
initDirty();
// 使用缓存
initMemoryCache();
// 启动服务器
const app = getApp(configPath, (eapp) => {
  // 万能跨域
  openCors(eapp);
  // 接口文档
  createApiDoc(eapp, getApiRouter, pathCN as any);
});
app.use("/public", express.static(path.join(__dirname, "./public/")));
// 404兜底
app.all("*", (_req: MasReq, res: MasRes) => {
  res.return(404, 0, 404);
});
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.return("服务器内部错误!");
});
app.listen(serverConfig.port, () => {
  console.log(`地址：http://localhost:${serverConfig.port}`);
  console.log(`接口文档地址：http://localhost:${serverConfig.port}/_mas_doc`);
});
